package com.huabo.monitor.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.hbfk.entity.DealUserToken;
import com.hbfk.entity.TblStaffUtil;
import com.hbfk.util.JsonBean;
import com.hbfk.util.ResponseFormat;
import com.huabo.monitor.oracle.entity.*;
import com.huabo.monitor.service.OrganizationService;
import com.huabo.monitor.service.TblAssEleCategoryService;
import com.huabo.monitor.service.TblAssesscategoryService;
import com.huabo.monitor.service.TblAssesstempleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.ServletConfigAware;

import javax.annotation.Resource;
import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;

@RestController
@Api(value = "评价模板", tags = {"评价模板相关"})
@RequestMapping(value = "/nbkz")
@Slf4j
public class AssessmentTemplateController  {

    private static final Logger logger = LoggerFactory.getLogger(AssessmentTemplateController.class);

    @Resource
    private TblAssesstempleService tblAssesstempleService;

    @Resource
    private OrganizationService organizationService;

    @Resource
    private TblAssesscategoryService tblAssesscategoryService;

    @Resource
    private TblAssEleCategoryService tblAssEleCategoryService;

    /**
     * 评价模板
     *
     * @return
     */
    @RequestMapping(value = "/gzdg/def_tmpl_list")
    @ApiOperation("评价模板列表-内容页面分页功能")
    public JsonBean getgzdgBasicList(HttpServletRequest request,
                                     @ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token,
                                     @ApiParam(name = "pageNumber", value = "分页当前页数", required = false) @RequestParam(value = "pageNumber", required = false, defaultValue = "1") Integer pageNumber,
                                     @ApiParam(name = "pageSize", value = "每页记录数", required = false) @RequestParam(value = "pageSize", required = false, defaultValue = "15") Integer pageSize,
                                     @ApiParam(name = "templeNumber", value = "模板编号条件", required = false) @RequestParam(value = "templeNumber", required = false) String templeNumber,
                                     @ApiParam(name = "templename", value = "模板名称条件", required = false) @RequestParam(value = "templename", required = false) String templename) {

        JsonBean jsonBean = null;
        try {
            TblAssesstemple tblAssesstemple = new TblAssesstemple();
            tblAssesstemple.setTempleNumber(templeNumber);
            tblAssesstemple.setTemplename(templename);
            jsonBean = tblAssesstempleService.findByPageInfo(pageNumber, pageSize, tblAssesstemple);
        } catch (Exception e) {
            e.printStackTrace();
            ResponseFormat.retParam(0, 1000, e.getMessage());
        }
        return jsonBean;

    }

    /**
     * 新建评价模板 || 跟新评价模板
     *
     * @param request
     * @return
     */
    @PostMapping(value = "/gzdg/def_tmpl_index", produces = "application/json; charset=utf-8")
    @ApiOperation("新建评价模板 || 跟新评价模板")
    public JsonBean gzdg_def_tmpl_index(@ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token,
                                        @ApiParam(name = "tblAssesstemple" , value = "实体类") TblAssesstemple tblAssesstemple,
                                        @ApiParam(name = "tmplId",value = "评价模板id", required = false) @RequestParam(value = "tmplId",required = false) BigDecimal tmplId,
                                        HttpServletRequest request) {
        logger.info("内控合规--内控工具--评价模板--新建--保存---start");
        //TblOrganization attribute1 = (TblOrganization) request.getSession().getAttribute("hbOrgEntity");
        TblStaffUtil loginStaff = null;
        try {
            loginStaff = DealUserToken.parseUserToken(token);
            if(loginStaff == null) {
                return ResponseFormat.retParam(0,20006,null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ResponseFormat.retParam(1,1000,e.getMessage());
        }
        BigDecimal orgid = loginStaff.getOrgid();
        if (null == tmplId) {
            //如果tmplId 为空 就是新增
            if (StringUtils.isNotBlank(tblAssesstemple.getReorg())
                    && StringUtils.isNotBlank(tblAssesstemple.getTempleNumber())) {
                String[] orgids = tblAssesstemple.getReorg().split(",");
                Set<TblOrganization> list = new HashSet<TblOrganization>();
                for (String string : orgids) {
                    TblOrganization organization = organizationService.findById(string);
                    if (null != organization) {
                        list.add(organization);
                    }
                }
                logger.info("通过模板编号，公司id查询评价模板");
                // 通过模板编号，公司id查询评价模板
                List<TblAssesstemple> assesstemples = tblAssesstempleService
                        .getTmplByNumber(tblAssesstemple.getTempleNumber(), orgid);
                if (assesstemples.size() == 0) {// 如果该编号在该公司不存在,保存
                    logger.info("保存评价模板");
//                    tblAssesstemple.setStaff(loginStaff.getStaffid());
//                    tblAssesstemple.setModifyDateTime(new Date());
//                    tblAssesstemple.setTblComany(loginStaff.getOrgid().toString());
                    tblAssesstemple.setOrganizations(list);
                    return tblAssesstempleService.add(tblAssesstemple);
                } else {
                    //return JsonBean.error("模板编号不能有重复");
                    return ResponseFormat.retParam(0, "模板编号不能有重复", "模板编号不能有重复");
                }
            }
        } else {
            //如果tmplId 不为空 就是更新
            if (StringUtils.isNotBlank(tblAssesstemple.getReorg())) {
                String[] orgids = tblAssesstemple.getReorg().split(",");
                Set<TblOrganization> list = new HashSet<TblOrganization>();
                for (String string : orgids) {
                    TblOrganization organization = organizationService.findById(string);
                    if (null != organization) {
                        list.add(organization);
                    }
                }
//                tblAssesstemple.setStaff(loginStaff.getStaffid());
//                tblAssesstemple.setTblComany(loginStaff.getOrgid().toString());
                tblAssesstemple.setOrganizations(list);
                tblAssesstemple.setModifyDateTime(new Date());
                return tblAssesstempleService.modify(tblAssesstemple);

            }
        }
        // mav.setViewName("nbkz/gzdg/def_tmpl_index");
        // mav.addObject("tmplId", tmplId);
        // return mav;
        //return JsonBean.error("保存失败");
        return ResponseFormat.retParam(0, 1000, "保存失败");
    }

    /**
     * 模板删除
     *
     * @return
     */
    @PostMapping(value = "/gzdg/def_tmpl_del", produces = "application/json; charset=utf-8")
    public JsonBean gzdg_def_tmpl_del(@ApiParam(name = "tmplId", value = "模板id", required = true) @RequestParam(value = "tmplId", required = true) String tmplId) {
        String[] ids = tmplId.split(",");
        String errorMsg = "";
        for (String id : ids) {
            BigDecimal decimal = new BigDecimal(id);
            TblAssesstemple assesstemple = tblAssesstempleService.findByid(decimal);
            if (null != assesstemple) {
                if (assesstemple.getTblAssesses().size() > 0) {
                    // return JsonBean.error("模板已经在使用，不能删除");
                    errorMsg += assesstemple.getTemplename() + ",";
                } else {
                    List<TblAssEleCategory> assEleCategories = tblAssEleCategoryService
                            .getAssesscategoryByMuBanId(decimal);
                    tblAssEleCategoryService.delete(assEleCategories);
                    tblAssesscategoryService.deleteByTempleId(decimal);
                    tblAssesstempleService.delete(assesstemple.getAsstemid());
                }
            }
        }
        if (StringUtils.isNotBlank(errorMsg)) {
            //return JsonBean.success("模板:" + errorMsg + "正在使用不能删除！");
            return ResponseFormat.retParam(0, 1000, "模板:" + errorMsg + "正在使用不能删除！");
        } else {
            //return JsonBean.success("删除成功");
            return ResponseFormat.retParam(1, 200, "删除成功");
        }
    }


    /**
     * copy 评价模板
     * @param token
     * @param tblAssesstemple
     * @param beforeTempId
     * @return
     */
    @RequestMapping(value = "/gzdg/def_tmpl_copy", produces = "application/json; charset=utf-8")
    public @ResponseBody String tempCopy(@ApiParam(name = "token", value = "登录用户token", required = true) @RequestHeader("token") String token,
                                         TblAssesstemple tblAssesstemple,
                                         BigDecimal beforeTempId) {
//        if (StringUtils.isNotBlank(tblAssesstemple.getReorg())
//                && StringUtils.isNotBlank(tblAssesstemple.getTempleNumber())) {
//            String[] orgids = tblAssesstemple.getReorg().split(",");
//            Set<TblOrganization> list = new HashSet<TblOrganization>();
//            List<TblAssEleCategory> aec = new ArrayList<TblAssEleCategory>();
//            for (String string : orgids) {
//                TblOrganization organization = this.organizationService.findById(string);
//                if (null != organization) {
//                    list.add(organization);
//                }
//            }
//            TblOrganization attribute = (TblOrganization) request.getSession().getAttribute("hbOrgEntity");// 选则的机构
//
//            List<TblAssesstemple> assesstemples = this.tblAssesstempleService
//                    .getTmplByNumber(tblAssesstemple.getTempleNumber(), attribute.getOrgid());
//            if (assesstemples.size() == 0) {
//                TblStaff tblStaff = (TblStaff) request.getSession().getAttribute("longUser");
//                tblAssesstemple.setStaff(tblStaff);
//                tblAssesstemple.setModifyDateTime(new Date());
//                tblAssesstemple.setOrganizations(list);
//                tblAssesstemple.setTblComany(attribute);
//                // 原来模板
//                // TblAssesstemple assesstemple =
//                // this.tblAssesstempleService.findByid(beforeTempId);
//                BigDecimal tmplId = (BigDecimal) this.tblAssesstempleService.add(tblAssesstemple);
//                TblAssesstemple tblAssesstempleCopy = this.tblAssesstempleService.findByid(tmplId);
//                List<TblAssesscategory> treeRoot = tblAssesscategoryService.getTreeRoot(beforeTempId);
//                for (TblAssesscategory tblAssesscategory : treeRoot) {
//                    TblAssesscategory tblAssesscategorycopy = new TblAssesscategory();
//                    tblAssesscategorycopy.setTblAssesstemple(tblAssesstempleCopy);
//                    tblAssesscategorycopy.setCatDes(tblAssesscategory.getCatDes());
//                    tblAssesscategorycopy.setCatname(tblAssesscategory.getCatname());
//                    tblAssesscategorycopy.setCatweight(tblAssesscategory.getCatweight());
//                    tblAssesscategorycopy.setTblAssesstemple(tblAssesstempleCopy);
//                    Serializable serializable = this.tblAssesscategoryService.add(tblAssesscategorycopy);
//                    TblAssesscategory addId = this.tblAssesscategoryService
//                            .get(new BigDecimal(serializable.toString()));
//                    Set<TblAssEleCategory> categories = tblAssesscategory.getAssEleCategories();
//                    if (categories.size() > 0) {
//                        for (TblAssEleCategory tblAssEleCategory : categories) {
//                            TblAssesselement assesselement = tblAssEleCategory.getAssesselement();
//                            TblAssEleCategory assEleCategory = new TblAssEleCategory();
//                            assEleCategory.setAssesscategory(addId);
//                            assEleCategory.setAssesselement(assesselement);
//                            aec.add(assEleCategory);
//                        }
//                    }
//                    List<TblAssesscategory> treeNode = tblAssesscategoryService
//                            .getTreeByNodeId(tblAssesscategory.getAsscatid());
//                    for (TblAssesscategory tblAssesscategory2 : treeNode) {
//                        for (TblAssesscategory tblAssesscategory3 : treeNode) {
//                            TblAssesscategory tblAssesscategorycopy1 = new TblAssesscategory();
//                            tblAssesscategorycopy1.setTblAssesstemple(tblAssesstempleCopy);
//                            tblAssesscategorycopy1.setCatDes(tblAssesscategory3.getCatDes());
//                            tblAssesscategorycopy1.setCatname(tblAssesscategory3.getCatname());
//                            tblAssesscategorycopy1.setCatweight(tblAssesscategory3.getCatweight());
//                            tblAssesscategorycopy1.setTblAssesstemple(tblAssesstempleCopy);
//                            tblAssesscategorycopy1.setFatherasscatid(new BigDecimal(serializable.toString()));
//                            Serializable serializable1 = this.tblAssesscategoryService.add(tblAssesscategorycopy1);
//                            TblAssesscategory assesscategory = this.tblAssesscategoryService
//                                    .get(new BigDecimal(serializable1.toString()));
//                            Set<TblAssEleCategory> categoriess = tblAssesscategory2.getAssEleCategories();
//                            if (categoriess.size() > 0) {
//                                for (TblAssEleCategory tblAssEleCategory : categoriess) {
//                                    TblAssesselement assesselement = tblAssEleCategory.getAssesselement();
//                                    TblAssEleCategory assEleCategory = new TblAssEleCategory();
//                                    assEleCategory.setAssesscategory(assesscategory);
//                                    assEleCategory.setAssesselement(assesselement);
//                                    aec.add(assEleCategory);
//                                }
//                            }
//                        }
//                        treeNode = tblAssesscategoryService.getTreeByNodeId(tblAssesscategory2.getAsscatid());
//                    }
//                }
//                this.tblAssEleCategoryService.saveList(aec);
//                return JsonBean.success(tmplId);
//            } else {
//                return JsonBean.error("模板编号不能有重复");
//            }
//        }
        return JsonBean.error("请完善信息！");
    }

}
